//
//  PEInputOutputVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/10/25.
//

#import "RHInputVC.h"
#import "RHInputHeaderView.h"
#import "RHInputRealTimeDataCell.h"
#import "RHStringDataCell.h"
#import "DevChartParamsModel.h"
#import "SYChartTool.h"
#import "DevChartModel.h"
#import "DeviceChartFieldModel.h"
#import "WSDatePickerView.h"
#import "RHStringFullChartVC.h"

@interface RHInputVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) NSArray *titleArr;

@property (nonatomic ,strong) UITableView *tableView;

@property(nonatomic, strong) RHInputHeaderView *headerView;

@property (nonatomic ,strong) DevChartParamsModel *chartParamsModel;
//实时数据
@property (nonatomic, strong) NSDictionary *realDataDic;
//0电流  1电压  2功率
@property (nonatomic, assign) NSInteger typeIndex;
@end

@implementation RHInputVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    [self createData];
    [self setupUI];
    [self getInOutData];
    [self getRealTimeData];
    [self getInChartData];
}

-(void)createData
{
    NSDictionary *dict = [SYChartTool readLocalJsonFileWithName:@"DeviceInput"];
    self.chartParamsModel = [DevChartParamsModel yy_modelWithDictionary:dict];
    
    for (DevChartModel *chartModel in self.chartParamsModel.chartList) {
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%zd",(NSInteger)interval];
        
        NSMutableArray *keys = [NSMutableArray array];
        for (DeviceChartFieldModel *fileld in chartModel.selectArray) {
            [keys addObject:fileld.keyName];
        }
        NSMutableDictionary *mtbDic = [NSMutableDictionary dictionary];
        [keys enumerateObjectsUsingBlock:^(NSString  *_Nonnull key, NSUInteger idx, BOOL * _Nonnull stop) {
            [mtbDic setObject:@"" forKey:key];
        }];
        [mtbDic setObject:@"" forKey:@"time"];
       
        chartModel.allDataArray = @[mtbDic];
        chartModel.xTitlesArray = @[@""];
    }
}

#pragma mark ----------- network ------------
//顶部数据
-(void)getInOutData
{
    [BaseModel startGetWithCompletionAPIKey:H_getInOutData argument:@{@"deviceId":self.deviceModel.deviceId} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            self.headerView.dic = request.responseJSONObject[@"data"];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
                
    }];
}

//实时数据
-(void)getRealTimeData
{
    
    [BaseModel startGetWithCompletionAPIKey:H_getRealTimeData argument:@{@"deviceId":self.deviceModel.deviceId} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            self.realDataDic = request.responseJSONObject[@"data"];
            [self.tableView reloadData];
        }

    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

//曲线数据
-(void)getInChartData
{
    DevChartModel *chartModel = self.chartParamsModel.chartList[self.typeIndex];
    
    NSString *type = @"";
    if(chartModel.timeType == TimeType_Day ){
        type = @"Power";
    }else if(chartModel.timeType == TimeType_Month){
        type = @"Electricity";
    }else if(chartModel.timeType == TimeType_Year){
        type = @"Voltage";
    }
    
    NSMutableArray *keys = [NSMutableArray array];
    [chartModel.selectArray enumerateObjectsUsingBlock:^(DeviceChartFieldModel  *_Nonnull fieldModel, NSUInteger idx, BOOL * _Nonnull stop) {
        [keys addObject:fieldModel.keyName];
    }];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSInteger currentTime = [date timeIntervalSince1970]*1000;
    NSDictionary *para = @{@"currentTime":@(currentTime),
                           @"dateRange":type,
                           @"deviceId":self.deviceModel.deviceId,
                           @"startTimestamp":@"",
                           @"endTimestamp":@"",
                           @"endpointSn":@"",
                           @"endpointTypeCode":@"",
                           @"keyCodes":keys,
                           @"timeZone":zone.name
    };
    [QMUITips showLoadingInView:self.view];
    [BaseModel startWithCompletionAPIKey:H_getInChartData argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
         
        if(resultModel.code == 200){
            chartModel.allDataArray = request.responseJSONObject[@"data"];
            [self.tableView reloadData];
        }
        
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
    
}



-(void)setupUI
{
    self.titleArr = @[@"实时数据",@"组串数据"];
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setBackgroundColor:UIColor.clearColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    _tableView.tableHeaderView = self.headerView;
    [_tableView registerClass:[RHInputRealTimeDataCell class] forCellReuseIdentifier:@"PERealTimeDataCell"];
    [_tableView registerClass:[RHStringDataCell class] forCellReuseIdentifier:@"RHStringDataCell"];
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(10, 0, 0, 0));
    }];
    
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
    }
}

#pragma mark ------------ TableViewDelegate ------------------
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.titleArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
   
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = kView;
  
    UILabel *titleLab = [[QMUILabel alloc]init];
    titleLab.font = kBOLDSYSTEMFONT(18);
    titleLab.textColor = kColorRGB(0, 0, 0);
    titleLab.textAlignment = NSTextAlignmentLeft;
    titleLab.text = self.titleArr[section];
    [headView addSubview:titleLab];
    
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(headView).offset(15);
        make.bottom.mas_offset(-10);
     }];
    
   return headView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    kWeakSelf;
    if(indexPath.section == 0){
        RHInputRealTimeDataCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PERealTimeDataCell"];
        cell.dic = self.realDataDic;
        return cell;
    }else if (indexPath.section == 1){
        RHStringDataCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHStringDataCell"];
        cell.chartModel = self.chartParamsModel.chartList[self.typeIndex];
        
        //选择参数
        cell.selectTopToolBlock = ^(NSInteger index) {
            [weakSelf selectTopTool:index atIndexpath:indexPath];
        };
        
        cell.subTimeBlock = ^{//日期往前
            [weakSelf subTimeAction:indexPath];
        };
        
        cell.addTimeBlock = ^{//日期往后
            [weakSelf addTimeAction:indexPath];
        };
        
        cell.changeTimeBlock = ^{//选择日期
            [weakSelf changeDate:indexPath];
        };
        
        //全屏
        cell.fullChartBlock = ^{
            [weakSelf fullAction:indexPath.section];
        };
        
        
        
        return cell;
    }
    return [UITableViewCell new];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
}


-(RHInputHeaderView *)headerView
{
    if(!_headerView){
        _headerView = [[RHInputHeaderView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, kScaleW(70)*2+15)];
        _headerView.backgroundColor = CFTabViewBgColor;
    }
    return _headerView;
}

#pragma mark ----------------- Action --------------------
#pragma mark ----- 参数 , 年 , 月 , 日选项 -------------
//工具选择项
- (void)selectTopTool:(NSInteger)index atIndexpath:(NSIndexPath *)indexpath{
    self.typeIndex = index;
    DevChartModel *chartModel = self.chartParamsModel.chartList[index];
    chartModel.timeType = TimeType_Day;
    NSDate *date = [NSDate date];
    NSTimeInterval interval = [date timeIntervalSince1970];
    chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
    chartModel.params = chartModel.dayParams;
    
    [self getInChartData];
    
}
#pragma mark ------ 选择日期 ------
//变更日期
- (void)changeDate:(NSIndexPath *)indexpath{
    DevChartModel *chartModel = self.chartParamsModel.chartList[self.typeIndex];
   
    WSDateStyle dataStyle = DateStyleShowYearMonthDay;
    if (chartModel.timeType == TimeType_Day) {
        dataStyle = DateStyleShowYearMonthDay;
    }else if (chartModel.timeType == TimeType_Month){
        dataStyle = DateStyleShowYearMonth;
    }else if (chartModel.timeType == TimeType_Year){
        dataStyle = DateStyleShowYearMonthDay;
    }

    @weakify(self);
    WSDatePickerView *datePickerV = [[WSDatePickerView alloc] initWithDateStyle:dataStyle CompleteBlock:^(NSDate *selectDate) {
        @strongify(self);
        //NSString *currentDate = [selectDate stringWithFormat: dateFormatStr];//年-月-日-时-分
        NSUInteger timeSp = [selectDate timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)timeSp];
        
        [self getInChartData];
    }];
    datePickerV.dateLabelColor = FontColor(@"#3ECE80");//年-月 颜色
    datePickerV.datePickerColor = UIColorBlack;//滚轮日期颜色
    datePickerV.doneButtonColor = UIColor.blackColor;//确定按钮的颜色
    if (chartModel.timeType == TimeType_Day) {
        datePickerV.maxLimitDate = [NSDate date];
        datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-5 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
    }else if (chartModel.timeType == TimeType_Month){

    }else if (chartModel.timeType == TimeType_Year){
        datePickerV.maxLimitDate = [NSDate date];
        datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-5 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
    }
    [datePickerV show];
}
#pragma mark ------ 后一天 -------
//日期累加
- (void)addTimeAction:(NSIndexPath *)indexpath{
    DevChartModel *chartModel = self.chartParamsModel.chartList[self.typeIndex];

    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSDate *nextDate;
    if (chartModel.timeType == TimeType_Day) {
        nextDate = [date dateByAddingDays:1];
    }else if (chartModel.timeType == TimeType_Month){
        nextDate = [date dateByAddingMonths:1];
    }else if (chartModel.timeType == TimeType_Year){
        nextDate = [date dateByAddingYears:1];
    }
    NSTimeInterval interval = [nextDate timeIntervalSince1970];
    chartModel.curTime = [NSString stringWithFormat:@"%ld",(long)interval];
    
    [self getInChartData];
}

#pragma mark ------ 前一天 -------
//日期累减
- (void)subTimeAction:(NSIndexPath *)indexpath{
    DevChartModel *chartModel = self.chartParamsModel.chartList[self.typeIndex];

    if (chartModel.timeType == TimeType_Total) {
        return;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSDate *nextDate;
    if (chartModel.timeType == TimeType_Day) {
        nextDate = [date dateBySubtractingDays:1];
    }else if (chartModel.timeType == TimeType_Month){
        nextDate = [date dateBySubtractingMonths:1];
    }else if (chartModel.timeType == TimeType_Year){
        nextDate = [date dateBySubtractingYears:1];
    }
    NSTimeInterval interval = [nextDate timeIntervalSince1970];
    chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
    
    [self getInChartData];
}


- (void)fullAction:(NSInteger)index{
    DevChartModel *chartModel = self.chartParamsModel.chartList[self.typeIndex];
    
    NSInteger type = 2;
    if (chartModel.monthParams.count>0) {
        type = 1;
    }
    if (chartModel.yearParams.count>0) {
        type = 0;
    }
 
    RHStringFullChartVC *vc = [[RHStringFullChartVC alloc] initWithModel:self.chartParamsModel typeIndex:self.typeIndex toolType:type deviceId:self.deviceModel.deviceId];
    [self.navigationController pushViewController:vc animated:NO];
    
    
}


#pragma mark - JXCategoryListContentViewDelegate
/**
 实现 <JXCategoryListContentViewDelegate> 协议方法，返回该视图控制器所拥有的「视图」
 */
- (UIView *)listView {
    return self.view;
}
@end
